<template>
    <div class="system-role-management" style="padding:0 10px">
        <!-- <div class="title_container">角色管理</div> -->
        <el-row>
            <el-col :span="24">
                <div class="btnContainer">
                    <el-button type="primary" @click="addItem">新增</el-button>
                </div>
            </el-col>
            <el-col :span="24">
                <div class="table-wrap">
                    <el-table border :data="treeTableJson" highlight-current-row>
                        <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
                        <el-table-column label="角色名" property="role_name" align="center"></el-table-column>
                        <el-table-column label="角色描述" property="role_discp" align="center"></el-table-column>
                        <el-table-column label="操作" property="resource_name" align="center" width="400">
                            <template slot-scope="scope">
                                <el-button @click="changeItem(scope.row)" type="text" class="color_blue">修改</el-button>
                                <el-button @click="deleteItem(scope.row)" type="text" class="color_blue">删除</el-button>
                                <el-button @click="jurisdictionItem(scope.row)" type="text" class="color_blue">权限
                                </el-button>
                                <el-button @click="chooseAuthority(scope.row)" type="text" class="color_blue">后台模块
                                </el-button>
                                <!-- <el-button
                                    @click="choosePhoneModule(scope.row)"
                                    type="text"
                                    class="color_blue"
                                >手机模块</el-button> -->
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination :paginationData="paginationData" @paginationDataNew="paginationDataNew"
                        v-if="this.paginationData.totalNum"></pagination>
                </div>
            </el-col>
        </el-row>
        <!-- 新增角色dialog弹窗 -->
        <el-dialog title="新增角色" :visible.sync="addshow" :close-on-click-modal="false" @close="dialogClose('addForm')">
            <el-form label-width="150px" :model="addForm" :rules="addRules" ref="addForm">
                <el-form-item label="角色名称" prop="role_name">
                    <el-input maxlength="20" v-model="addForm.role_name"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="role_discp">
                    <el-input maxlength="200" type="textarea" v-model="addForm.role_discp"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="addshow = false" size="small">取 消</el-button>
                <el-button class="btn-class" type="primary" @click="addcommit" size="small">确 定</el-button>
            </div>
        </el-dialog>
        <!-- -------------------------------------- -->
        <!-- 修改角色dialog弹窗 -->
        <el-dialog title="修改角色" :visible.sync="editshow" :close-on-click-modal="false" @close="dialogClose('editForm')">
            <el-form label-width="150px" :model="editForm" :rules="editRules" ref="editForm">
                <el-form-item label="角色名称" prop="role_name">
                    <el-input maxlength="20" v-model="editForm.role_name"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="role_discp">
                    <el-input maxlength="200" type="textarea" v-model="editForm.role_discp"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="editshow = false" size="small">取 消</el-button>
                <el-button class="btn-class" type="primary" @click="editcommit" size="small">确 定</el-button>
            </div>
        </el-dialog>
        <!-- -------------------------------------- -->
        <!-- table角色权限 -->
        <el-dialog title="角色权限" :visible.sync="jurisdictionshow" :top="dialogTop" :close-on-click-modal="false">
            <el-button type="primary" @click="jurisdictioncommit" :disabled="this.$store.state.btnType" size="small">保存
            </el-button>
            <el-tree :data="myTree" :props="defaultProps" :default-expand-all="true" show-checkbox node-key="menu_id"
                :default-checked-keys="checkedJson" ref="tree"></el-tree>
        </el-dialog>
        <!-- ----------------------------------------- -->
        <!-- 权限模块 -->
        <el-dialog @open="openAuthorCb" title="权限模块" :visible.sync="authorityShow" :close-on-click-modal="false">
            <div class="system-list-wrap" v-loading="diaLoading">
                <div @click="chooseAuthor(item)" :class="['system-item', { 'active-author': item.status }]"
                    v-for="item in systemList" :key="item.code_value">
                    {{ item.code_name }}
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button class="btn-class" type="primary" @click="saveRoleSys_codes">确 定</el-button>
                <el-button @click="authorityShow = false">取 消</el-button>
            </span>
        </el-dialog>
        <!-- ----------------------------------------- -->
        <!-- 手机模块 -->
        <el-dialog @open="openPhoneCb" title="手机模块" :visible.sync="phoneModuleShow" :close-on-click-modal="false">
            <div class="system-list-wrap" v-loading="diaLoading">
                <div @click="choosePhone(item)" :class="['system-item', { 'active-author': item.status }]"
                    v-for="item in phoneList" :key="item.code_value">
                    {{ item.code_name }}
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button class="btn-class" type="primary" @click="saveRolePhoneModule">确 定</el-button>
                <el-button @click="phoneModuleShow = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import * as api from "@/http/admin-api.js";
import pagination from "@/comon/components/pagination.vue";
export default {
    components: {
        pagination
    },
    data() {
        return {
            treeTableJson: [],
            paginationData: {
                pageNum: "",
                pageSize: "",
                totalNum: ""
            },

            addshow: false,
            addForm: {
                role_name: "",
                role_discp: ""
            },
            addRules: {
                role_name: [
                    {
                        required: true,
                        message: "请填写资源名称",
                        trigger: "blur"
                    }
                ],
                role_discp: [
                    {
                        required: true,
                        message: "请输入资源url",
                        trigger: "blur"
                    }
                ]
            },
            editshow: false,
            editForm: {
                role_name: "",
                role_discp: ""
            },
            editRules: {
                role_name: [
                    {
                        required: true,
                        message: "请填写资源名称",
                        trigger: "blur"
                    }
                ],
                role_discp: [
                    {
                        required: true,
                        message: "请输入资源url",
                        trigger: "blur"
                    }
                ]
            },

            jurisdictionshow: false,
            myTree: [],
            defaultProps: {
                children: "childlist",
                label: "menu_name"
            },
            dialogTop: "20px",
            menuList: "",
            checkedJson: [],
            role_id: "",
            systemList: [],
            authorityShow: false,
            selectRow: {},
            diaLoading: false,
            phoneList: [],
            phoneModuleShow: false
        };
    },
    methods: {
        /**
         * 选择权限模块弹窗
         */
        chooseAuthority(row) {
            this.selectRow = row;
            this.authorityShow = true;
        },
        /**
         * 选择手机权限模块弹窗
         */
        choosePhoneModule(row) {
            this.selectRow = row;
            this.phoneModuleShow = true;
        },
        /**
         * 选择具体权限模块
         */
        chooseAuthor(row) {
            this.systemList.forEach(item => {
                if (row.code_value === item.code_value) {
                    item.status = !item.status;
                }
            });
        },
        /**
         * 选择具体权限模块
         */
        choosePhone(row) {
            this.phoneList.forEach(item => {
                if (row.code_value === item.code_value) {
                    item.status = !item.status;
                }
            });
        },
        /**
         * 权限模块弹窗打开回调函数
         */
        openAuthorCb() {
            this.getSystemList();
        },
        openPhoneCb() {
            this.getPhoneList();
        },
        getSystemList() {
            this.diaLoading = true;
            api.getCodelistByKind({
                code_kind: "sys_code"
            }).then(res => {
                if (res) {
                    let systemList = res.bus_json[0].codelists;
                    if (systemList) {
                        systemList.forEach(item => {
                            item.status = false;
                        });
                    }
                    this.systemList = systemList;
                    this.getRoleSys_codes();
                }
                this.diaLoading = false;
            });
        },
        getPhoneList() {
            this.diaLoading = true;
            api.getCodelistByKind({
                code_kind: "phone_module"
            }).then(res => {
                if (res) {
                    let phoneList = res.bus_json[0].codelists;
                    if (phoneList) {
                        phoneList.forEach(item => {
                            item.status = false;
                        });
                    }
                    this.phoneList = phoneList;
                    this.getRolePhoneModule();
                }
                this.diaLoading = false;
            });
        },
        /**
         * 获取权限模块信息
         */
        getRoleSys_codes() {
            api.getRoleSys_codes({
                role_id: this.selectRow.role_id
            }).then(res => {
                if (res && res.bus_json && res.bus_json.list) {
                    let list = res.bus_json.list;
                    list.forEach(item => {
                        this.systemList.forEach(codeList => {
                            if (codeList.code_value === item) {
                                codeList.status = !codeList.status;
                            }
                        });
                    });
                }
            });
        },
        getRolePhoneModule() {
            api.getRolePhoneModule({
                role_id: this.selectRow.role_id
            }).then(res => {
                if (res && res.bus_json && res.bus_json.list) {
                    let list = res.bus_json.list;
                    list.forEach(item => {
                        this.phoneList.forEach(codeList => {
                            if (codeList.code_value === item) {
                                codeList.status = !codeList.status;
                            }
                        });
                    });
                }
            });
        },
        /**
         * 保存权限模块信息
         */
        saveRoleSys_codes() {
            let sys_codes = [];
            this.systemList.forEach(item => {
                if (item.status) {
                    sys_codes.push(item.code_value);
                }
            });
            this.diaLoading = true;
            api.saveRoleSys_codes({
                role_id: this.selectRow.role_id,
                sys_codes: sys_codes.join(";")
            }).then(res => {
                if (res) {
                    this.$message({
                        type: "success",
                        message: res.error_msg
                    });
                    this.authorityShow = false;
                    this.getRoleList();
                } else {
                    this.$message({
                        type: "success",
                        message: res.error_msg
                    });
                }
                this.diaLoading = false;
            });
        },
        saveRolePhoneModule() {
            let phone_modules = [];
            this.phoneList.forEach(item => {
                if (item.status) {
                    phone_modules.push(item.code_value);
                }
            });
            this.diaLoading = true;
            api.saveRolePhoneModule({
                role_id: this.selectRow.role_id,
                phone_modules: phone_modules.join(";")
            }).then(res => {
                if (res) {
                    this.$message({
                        type: "success",
                        message: res.error_msg
                    });
                    this.phoneModuleShow = false;
                    this.getRoleList();
                } else {
                    this.$message({
                        type: "success",
                        message: res.error_msg
                    });
                }
                this.diaLoading = false;
            });
        },
        // 获取角色列表
        getRoleList() {
            api.getRoleList({
                pageNum: this.paginationData.pageNum,
                pageSize: this.paginationData.pageSize
            }).then(res => {
                if (res) {
                    this.treeTableJson = res.bus_json.items;
                    this.paginationData.pageNum = res.bus_json.pageNum;
                    this.paginationData.pageSize = res.bus_json.pageSize;
                    this.paginationData.totalNum = res.bus_json.totalNum;
                }
            });
        },
        // 所有关闭dialog的清除验证的回调
        dialogClose(formName) {
            this.$nextTick(() => {
                this.$refs[formName].resetFields();
            });
        },
        // 分页器公共方法
        paginationDataNew(sth) {
            this.paginationData = sth;
            this.getRoleList();
        },
        // 新增角色提交
        addcommit() {
            api.saveRole({
                role_name: this.addForm.role_name,
                role_discp: this.addForm.role_discp
            }).then(res => {
                if (res) {
                    this.addshow = false;
                    this.getRoleList();
                }
            });
        },
        //新增按钮点击，dialog框显示
        addItem() {
            (this.addForm = {
                role_name: "",
                role_discp: ""
            }),
                (this.addshow = true);
        },
        // 角色列表内修改按钮
        changeItem(sth) {
            api.getRoleInfoById({
                role_id: sth.role_id
            }).then(res => {
                if (res) {
                    this.editshow = true;
                    this.editForm = {
                        role_name: res.bus_json.role_name,
                        role_discp: res.bus_json.role_discp,
                        role_id: res.bus_json.role_id
                    };
                }
            });
        },
        // 修改角色提交
        editcommit() {
            api.saveRole({
                role_name: this.editForm.role_name,
                role_discp: this.editForm.role_discp,
                role_id: this.editForm.role_id
            }).then(res => {
                if (res) {
                    this.editshow = false;
                    this.getRoleList();
                }
            });
        },
        // table内删除按钮
        deleteItem(sth) {
            this.$confirm("确认删除该数据？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    api.delRoleById({
                        role_id: sth.role_id
                    }).then(res => {
                        if (res) {
                            this.$message({
                                type: "success",
                                message: res.error_msg
                            });
                            this.getRoleList();
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "未删除"
                    });
                });
        },
        // 权限按钮点击
        jurisdictionItem(sth) {
            // 后台要的格式的tree选中
            this.menuList = "";
            // 数据json
            this.myTree = [];
            // tree选中json
            this.checkedJson = [];
            api.getAuthTree({
                role_id: sth.role_id
            }).then(res => {
                if (res) {
                    this.jurisdictionshow = true;
                    this.myTree = res.bus_json.list;
                    this.role_id = sth.role_id;
                    console.log(this.myTree);
                    this.recursive(this.myTree[0].childlist);
                }
            });
        },
        recursive(sth) {
            let len = sth.length;
            for (let i = 0; i < len; i++) {
                if (sth[i].childlist !== null && sth[i].childlist.length > 0) {
                    this.recursive(sth[i].childlist);
                } else {
                    if (sth[i].checked == 1) {
                        this.checkedJson.push(sth[i].menu_id);
                    }
                }
            }
        },
        jurisdictioncommit() {
            let leafData = this.$refs.tree.getCheckedNodes(true, false);
            for (let i = 0; i < leafData.length; i++) {
                this.menuList +=
                    leafData[i].menu_id + "#" + leafData[i].menu_level + ";";
            }
            this.menuList = this.menuList.slice(0, this.menuList.length - 1);
            api.saveAuthTree({
                role_id: this.role_id,
                resource_ids: this.menuList
            }).then(res => {
                if (res) {
                    this.$message({
                        type: "success",
                        message: res.error_msg
                    });
                    this.getRoleList();
                    this.jurisdictionshow = false;
                }
            });
        }
    },
    created() {
        this.getRoleList();
    },
    mounted() { }
};
</script>
<style lang="scss">
.system-role-management {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    background: #fff;
    // overflow-y: auto;

    .title_container {
        width: 100%;
        text-indent: 20px;
        text-align: left;
        font-size: 16px;
        line-height: 40px;
        height: 40px;
        color: #484848;
        border-bottom: 1px solid #efefef;
    }

    .btnContainer {
        text-align: right;
        margin: 20px 0;
    }

    .tableContainer {
        width: 100%;

        el-table {
            width: 100%;
        }
    }

    .color_green {
        color: #009788;
    }

    .color_red {
        color: red;
    }

    .color-orange {
        color: #fdc830;
    }

    .system-list-wrap {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .system-item {
        padding: 9px 24px;
        border: 1px solid #ededed;
        width: auto;
        margin-bottom: 17px;
        border-radius: 4px;
        cursor: pointer;
        color: #666;
        background: #ffffff;
    }

    .active-author {
        border: 1px solid #2193b0;
        color: #ffffff;
        background: #2193b0;
    }

    .table-wrap {
        width: 100%;
        height: calc(100% - 52px);
    }
}
</style>
